package com.tmt.im.manager.helper;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.awt.image.BufferedImage;
import java.text.MessageFormat;

/**
 * 二维码生成助手类
 *
 * @Description TODO
 * @Author wuyi
 * @Date 2024/8/23 11:20
 * @Version 1.0
 **/
public class QrCodeHelper {

    /**
     * 获取用户二维码URL地址
     *
     * @param apiPrefix
     * @param userId
     * @return
     */
    public static String getQrCodeUrl(String apiPrefix, Long userId) {
        if (userId != null){
            return MessageFormat.format("{0}/qrCode/{1}", apiPrefix, "" + userId);
        }
        return MessageFormat.format("{0}/qrCode/self", apiPrefix);
    }

    /**
     * 生成二维码数据。
     *
     * @param userId
     * @return
     * @throws WriterException
     */
    public static BufferedImage getQrCodeData(Long userId) throws WriterException {
        // 生成二维码
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode("" + userId, BarcodeFormat.QR_CODE, 300, 300);
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }

}
